define(function(require){
    $(function(){
    	/*---------- 流量资源——平台运营人员 ----------*/
        /* 表格 */
    	var bodyTemplate = ['<tr traffic_id="{traffic_id}">',
    	                    '<td class="txtc"><a href="/trp/resource/main/?traffic={traffic_id}" title="{position_name}">{position_name}</a></td>',
    	                    '<td class="txtc position_attrs">{position_attrs}</td>',
    	                    '<td class="txtc position_width">{width}</td>',
    	                    '<td class="txtc position_height">{height}</td>',
    	                    '<td class="txtc" max="{max}">{max}</td>',
    	                    '<td class="txtc media_name">{media_name}</td>',
    	                    '<td class="txtc circle">{media_attrs}</td>',
    	                    '<td class="txtc circle" start="{start}" end="{end}">{start} 至 {end}</td>',
    	                    '<td class="txtc pv">{pv}</td>',
    	                    '<td class="txtc click">{click}</td>',
    	                    '<td class="txtc shared">{shared}</td>',
	                     	'<td class="txtc">',
	                     		'<a class="ibtn setbtn disabled {material}" href="javascript:;" title="设置默认素材"><span class="glyphicon glyphicon-cog"></span></a>',
	                     		'<a class="ibtn relatedbtn" href="/trp/strategy/?traffic_id={traffic_id}" title="关联策略"><span class="glyphicon glyphicon-th-list"></span></a>',
                     		'</td>',
	                     '</tr>'].join('');
        
    	var date = $('[name=reservation]').val().split(' 至 ');
        var grid = Grid.init({
	            holder: 'trafficList',
	            bodyTemplate: bodyTemplate,
	            dataSource: '/trp/traffic/get_list',
	            pageTemplate: semi.grid.pageTemplate,
	            sendOnPageSize: true
	        });
        
        grid.modifyModel(function(data){
    		if(data.material!=0){
        		data.material = 'green';
        	}else{
        		data.material = '';
        	}
    	});
    	grid.onfilled(function(data){
        	var time = data.time;
        	$('#trafficList tbody tr').each(function(){
        		var $tr = $(this), start = $('[start]',$tr).attr('start'), end = $('[end]',$tr).attr('end');
        		if(moment(end).diff(moment(time))>=0){//未结束
        			$('.setbtn',$tr).removeClass('disabled');
        		}
        	});
        	$('.setbtn').each(function(){
        		if($(this).hasClass('green')){
        			$(this).attr('title','已设置默认素材');
        		}else{
        			$(this).attr('title','设置默认素材');
        		}
        	});
        	$('.ibtn').tooltip();
    	});
        
        /* 数据搜索 */
        var filterData = function(){
        	var txt = $('.searchbox-ipt').val(),
            	d = $('[name=reservation]').val().split(' 至 '),
            	size = $('.pageheader [name=measure]').val(),
            	width = '', height = '',
            	pageSize = 20;
        	
        	if(!semi.utils.isEmpty(size)){
	    		size = size.split('x');
	    		width = size[0];
	    		height = size[1];
	    	}
        	if($('select.page-size').size()>0){
        		pageSize = $('select.page-size').val();
        	}
            grid.send({
        		search_text: txt,
        		start: d[0],
        		end: d[1],
        		width: width,
	        	height: height,
        		pageSize: pageSize,
        		pageNo: 1
        	});
        };
        filterData();
        
        /* 日期选择 */
        $('input[name=reservation]').daterangepicker({
        	opens: 'left',
            format:'YYYY-MM-DD'
        }, function(start, end, label) {
        	console.log(start.toISOString(), end.toISOString(), label);
        	filterData();
        });
        
        //按名称、属性模糊搜索
        $('.pageheader .searchbox-btn').on('click', function(){
        	filterData();
        });
        $('.pageheader .searchbox-ipt').on('keyup', function(e){
        	if(e.keyCode==semi.keyCode.ENTER){
        		filterData();
        	}
        });
        
        //按尺寸搜索
        $('.pageheader [name=measure]').select2({
        	ajax: {
        		url: '/trp/position/get_position_size/',
        		results: function(data){
        			var resultArr = [{id:'', text:'全部尺寸'}];
        			$.each(data.data, function(i,n){
        				var val = n.width+'x'+n.height;
        				resultArr.push({id:val, text:val});
        			});
        			return {results: resultArr}
        		}
        	}
        }).on('change', filterData);
        
        /* 设置默认素材 */
        var $classify = require('./common/classify');
        $(document).on('click', '.setbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), traffic_id = $tr.attr('traffic_id'), data = {traffic_id: traffic_id}, minSum = parseInt($('[max]',$tr).attr('max'));
        	if($this.hasClass('disabled'))return;
        	$ajax.ajax({
        		url:'/static/trp/template/classify.html',
        		success: function(html){
        			$dialog({
        	        	title: '设置默认素材',
        	        	content: html,
        	        	onshow: function(){
        	        		$classify.init({
        	        			data: data,
        	        			getgroup: 1
        	        		});
        	        	},
        	        	okValue: '确定',
                    	ok: function(){
                    		var $d = this, $node = $(this.node);
                    			
                    		if(!$classify.check())return false;
                    		var dataArr = $classify.get(), mSum = 0;
                    		
                    		$.each(dataArr, function(i,n){
	            				var materials = [];
	            				$.each(n.materials, function(j, m){
	            					materials.push(m.id);
	            					mSum++;
	            				});
	            				n.materials = materials;
	            			});
                    		
                    		if(mSum!=0 && mSum<minSum){
                    			$dialog.alert('分组内素材数 【'+mSum+'】<b>小于</b> 广告位分栏数 【'+minSum+'】，请检查！','warning');
                    			return false;
                    		}
                    		
                    		$ajax.ajax({
                    			url: '/trp/material/set_default_material/',
                    			data: JSON.stringify({traffic_id:traffic_id, groups:dataArr}),
                        		contentType : "application/json",
                                type : 'POST',
                                dataType : 'json',
                    			success: function(data){
                    				$d.close().remove();
                					$dialog.alert((semi.utils.isEmpty(dataArr)?'清空':'设置')+'默认素材成功！','success');
                    			},
                    			error: function(){
                    				$d.close().remove();
                    				$dialog.alert((semi.utils.isEmpty(dataArr)?'清空':'设置')+'默认素材失败，请稍后重试！','warning');
                    			}
                    		});
                    		return false;
                        },
                        cancelValue: '取消',
                        cancel: function(){}
        	        }).showModal();
        		}
        	});
        });
    });
});